home *** CD-ROM | disk | FTP | other *** search
/ Reverse Code Engineering RCE CD +sandman 2000 / ReverseCodeEngineeringRceCdsandman2000.iso / RCE / Ebooks / Thinking in C++ V2 / C20 / TokenIterator.h < prev    next >
Encoding:
C/C++ Source or Header  |  2000-05-25  |  1.9 KB  |  79 lines

  1. //: C20:TokenIterator.h
  2. // From Thinking in C++, 2nd Edition
  3. // Available at http://www.BruceEckel.com
  4. // (c) Bruce Eckel 1999
  5. // Copyright notice in Copyright.txt
  6. #ifndef TOKENITERATOR_H
  7. #define TOKENITERATOR_H
  8. #include <string>
  9. #include <iterator>
  10. #include <algorithm>
  11. #include <cctype>
  12.  
  13. struct Isalpha { 
  14.   bool operator()(char c) { 
  15.     using namespace std; //[[For a compiler bug]]
  16.     return isalpha(c); 
  17.   }
  18. };
  19.  
  20. class Delimiters {
  21.   std::string exclude;
  22. public:
  23.   Delimiters() {}
  24.   Delimiters(const std::string& excl) 
  25.     : exclude(excl) {}
  26.   bool operator()(char c) {
  27.     return exclude.find(c) == std::string::npos;
  28.   }
  29. };
  30.  
  31. template <class InputIter, class Pred = Isalpha>
  32. class TokenIterator: public std::iterator<
  33.   std::input_iterator_tag,std::string,ptrdiff_t>{
  34.   InputIter first;
  35.   InputIter last;
  36.   std::string word;
  37.   Pred predicate;
  38. public:
  39.   TokenIterator(InputIter begin, InputIter end, 
  40.     Pred pred = Pred()) 
  41.     : first(begin), last(end), predicate(pred) {
  42.       ++*this; 
  43.   }
  44.   TokenIterator() {} // End sentinel
  45.   // Prefix increment:
  46.   TokenIterator& operator++() {
  47.     word.resize(0);
  48.     first = std::find_if(first, last, predicate);
  49.     while (first != last && predicate(*first))
  50.       word += *first++;
  51.     return *this;
  52.   }
  53.   // Postfix increment
  54.   class Proxy { 
  55.     std::string word;
  56.   public:
  57.     Proxy(const std::string& w) : word(w) {}
  58.     std::string operator*() { return word; } 
  59.   };
  60.   Proxy operator++(int) { 
  61.     Proxy d(word);
  62.     ++*this; 
  63.     return d; 
  64.   }
  65.   // Produce the actual value:
  66.   std::string operator*() const { return word; }
  67.   std::string* operator->() const {
  68.     return &(operator*()); 
  69.   }
  70.   // Compare iterators:
  71.   bool operator==(const TokenIterator&) { 
  72.     return word.size() == 0 && first == last; 
  73.   }
  74.   bool operator!=(const TokenIterator& rv) { 
  75.     return !(*this == rv);
  76.   }
  77. };
  78. #endif // TOKENITERATOR_H ///:~
  79.